import base64
import datetime
import os
import time, re
# import jieba
from Crypto.PublicKey import RSA
from bs4 import BeautifulSoup
import numpy as np
import matplotlib.pyplot as plt
from django.test import TestCase
import requests
import pandas as pd
import sqlite3 as sqlite3_db
import jqdatasdk
from jqdatasdk import get_all_securities
from sqlalchemy import create_engine
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.model_selection import cross_validate, cross_val_score, train_test_split
from sklearn import preprocessing, svm
from sklearn.linear_model import LinearRegression

from Crypto.PublicKey import RSA
from Crypto import Hash
import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5  # 用于签名/验签


def sign_with_private_key(plain_text, private_key):
    # 私钥签名
    signer_pri_obj = sign_PKCS1_v1_5.new(private_key)
    rand_hash = Hash.SHA256.new()
    rand_hash.update(plain_text.encode())
    signature = signer_pri_obj.sign(rand_hash)
    return signature


def verify_with_public_key(signature, plain_text, LOCAL_PUBLIC_RSA_KEY):
    # 公钥验签
    verifier = sign_PKCS1_v1_5.new(LOCAL_PUBLIC_RSA_KEY)
    _rand_hash = Hash.SHA256.new()
    _rand_hash.update(plain_text.encode())
    verify = verifier.verify(_rand_hash, signature)
    return verify  # true / false


def get_data_from_jqdata():
    data = get_all_securities(['index'])
    # data = pd.read_csv("../data/index_code.csv")
    data['market_index_code'] = data.index
    data.index = [x for x in range(len(data))]
    data['exchange_abbreviated_name'] = data['market_index_code'].map(lambda x: x.split('.')[1])
    data['market_index_code'] = data['market_index_code'].map(lambda x: x.split('.')[0])
    data['market_index_api_name'] = data['exchange_abbreviated_name'].map(lambda x: 'sh' if x == 'XSHG' else 'sz')

    data['market_index_abbreviated_name'] = data['name']
    data = data.drop('name', axis=1)
    data['market_index_name'] = data['display_name']
    data = data.drop('display_name', axis=1)
    data['market_index_class'] = data['exchange_abbreviated_name'].map(lambda x: 1 if x == 'XSHG' else 2)
    data['last_update_time'] = datetime.datetime.now().strftime("%Y-%m-%d")
    data = data[
        ['market_index_class', 'market_index_name', 'market_index_abbreviated_name', 'market_index_code',
         'market_index_api_name', 'last_update_time',
         'start_date', 'end_date', 'type', 'exchange_abbreviated_name']]
    print(data)
    # print(jqdatasdk.context.portfolio.cash)
    # stock_data=get_all_securities()
    data.to_csv("../data/market_index_code.csv", index=False)

    # "sw_l1": 申万一级行业
    # "sw_l2": 申万二级行业
    # "sw_l3": 申万三级行业
    # "jq_l1": 聚宽一级行业
    # "jq_l2": 聚宽二级行业
    # "zjw": 证监会行业


def send_mobile_message(account, password, msg, phone):
    data = {"account": account,
            "password": password,
            "msg": "【253云通讯】您的验证码是312321",
            "params": "4321",
            "phone": phone,
            }
    url = 'http://smssh1.253.com/msg/send/json'
    response = requests.post(url, json=data)
    print(response.content.decode('utf-8'))


if __name__ == "__main__":
    list_path = os.listdir("../data/stock_data")
    for old_file_path in list_path:
        try:
            file_name = old_file_path.split("_")
            old_file_path = "../data/stock_data/%s" % old_file_path
            yestoday_date = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
            new_file_path = "../data/stock_data/%s_%s_%s.csv" % (file_name[0], file_name[1], yestoday_date)
            os.rename(old_file_path, new_file_path)
            print("from:", old_file_path, "to:", new_file_path)
            # data = pd.read_csv(old_file_path)

            # new_data = data.drop_duplicates(['date'])
            # print("from: %s len:%s" % (old_file_path, len(data)), "to: %s len:%s" % (old_file_path, len(new_data)))

            # data.to_csv(old_file_path, index=False)
        except Exception as e:
            print(old_file_path, e)
            continue

    # auth_key = None
    # send_mobile_message('N6664837', '123456aaabbb', '', '18584892542')
    # with open("../data/auth_key.key") as key:
    #     auth_key = key.read().split(",")
    #     jqdatasdk.auth(auth_key[0], auth_key[1])
    # stocks = jqdatasdk.get_concept_stocks('GN036')
    # for stock in stocks:
    #     stock=stock.split('.')
    #     stock_code=stock[0]
    #     exchange_abbreviated_name=stock[1]
    #     print(stock_code,exchange_abbreviated_name)
    #     print(c_name)
    # data = jqdatasdk.get_concepts()
    # print(data)
    #     data['code']=data.index
    #     data.index=[x for x in range(len(data))]
    #     print(data.head())
    #     data.to_csv('../data/Conceptual.csv',index=False)
    # a.quant_rules.test_predict_model.feature_engineering(2)
    pass
